package fun.rockchen.controller;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import fun.rockchen.bean.NotificationEntity;
import fun.rockchen.dao.NotificationDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Rock Chen
 * @Description:
 * @date 2023/10/21 20:14
 */

@Component
//@EnableScheduling
public class NotificationTask {

    private final NotificationDao notificationDao;

    JPushClient jPushClient = new JPushClient("2d76195bca56995fecb5de00", "1cddba04b062f330428d8f1f");

    @Autowired
    public NotificationTask(NotificationDao notificationDao) {
        this.notificationDao = notificationDao;
    }

//    @PostConstruct
    @Scheduled(cron = "0 */1 * * * ?")
    public void checkTasks() {
        Date nowDate = new Date();
        SimpleDateFormat timeFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = timeFormat1.format(nowDate);
        List<NotificationEntity> notificationEntityList = notificationDao.getStatusChangeTask(date);
        System.out.println("this is data: "+notificationEntityList);
        if (!notificationEntityList.isEmpty()) {
            for (NotificationEntity notificationEntity : notificationEntityList) {
                PushPayload payload = PushPayload.newBuilder()
                        .setPlatform(Platform.all())
                        .setAudience(Audience.alias(notificationEntity.getUserId()))
                        .setOptions(Options.newBuilder().setApnsProduction(true).build())
                        .setNotification(Notification.newBuilder()
                                .addPlatformNotification(IosNotification.newBuilder()
                                        .setAlert("您的任务(" + notificationEntity.getTaskContent() + ")已经开始了！")
                                        .setBadge(1)
                                        .setSound("default")
                                        .build())
                                .build())
                        .build();

                try {
                    jPushClient.sendPush(payload);
                } catch (APIConnectionException | APIRequestException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

